<template>
  <div>
    <div class="imui-center-wrap" v-if="visible">
      <div class="imui-center">
        <div class="close" @click="close">
          <i class="el-icon-close"></i>
        </div>
        <lemon-imui
            :user="myUser"
            ref="IMUI"
            :hide-menu="hideMenu"
            :hide-menu-avatar="hideMenuAvatar"
            :hide-drawer="hideDrawer"
            @change-contact="handleChangeContact"
            @pull-messages="handlePullMessages"
            @message-click="handleMessageClick"
            @send="handleSend"
        >
          <template #cover>
            <div class="cover">
              <i class="lemon-icon-message"></i>
              <p>客服系统</p>
            </div>
          </template>
          <template #message-sidebar>
            <div class="bar-wrap">
              <div class="bar">客服</div>
            </div>
          </template>
        </lemon-imui>
      </div>
    </div>
  </div>
</template>

<script>
import {
  mapGetters
} from "vuex"

import {client} from './../../request/trade'
import path from "path";
import BASE64 from './../../utils/base64'
import store from "../../store";

const getTime = () => {
  return new Date().getTime();
};
const generateRandId = () => {
  return Math.random()
      .toString(36)
      .substr(-8);
};
const generateRandWord = () => {
  return Math.random()
      .toString(36)
      .substr(2);
};
const generateMessage = (toContactId = "", fromUser, msg) => {
  if (!fromUser) {
    fromUser = {
      id: "system",
      displayName: "系统测试",
      avatar: "http://upload.qqbodys.com/allimg/1710/1035512943-0.jpg"
    };
  }
  return {
    id: generateRandId(),
    status: "succeed",
    type: "text",
    sendTime: getTime(),
    content: msg,
    toContactId,
    fromUser
  };
};

const emojiList = [
  {"url": "100.gif", alt: "[微笑]"}, {"url": "101.gif", alt: "[伤心]"}, {
    "url": "102.gif",
    alt: "[美女]"
  }, {"url": "103.gif", alt: "[发呆]"}, {"url": "104.gif", alt: "[墨镜]"}, {
    "url": "105.gif",
    alt: "[哭]"
  }, {"url": "106.gif", alt: "[羞]"}, {"url": "107.gif", alt: "[哑]"}, {
    "url": "108.gif",
    alt: "[睡]"
  }, {"url": "109.gif", alt: "[哭]"}, {"url": "110.gif", alt: "[囧]"}, {
    "url": "111.gif",
    alt: "[怒]"
  }, {"url": "112.gif", alt: "[调皮]"}, {"url": "113.gif", alt: "[笑]"}, {
    "url": "114.gif",
    alt: "[惊讶]"
  }, {"url": "115.gif", alt: "[难过]"}, {"url": "116.gif", alt: "[酷]"}, {
    "url": "117.gif",
    alt: "[汗]"
  }, {"url": "118.gif", alt: "[抓狂]"}, {"url": "119.gif", alt: "[吐]"}, {
    "url": "120.gif",
    alt: "[笑]"
  }, {"url": "121.gif", alt: "[快乐]"}, {"url": "122.gif", alt: "[奇]"}, {"url": "123.gif", alt: "[傲]"},
  {"url": "124.gif", alt: "[饿]"}, {"url": "125.gif", alt: "[累]"}, {"url": "126.gif", alt: "[吓]"}, {
    "url": "127.gif",
    alt: "[汗]"
  }, {"url": "128.gif", alt: "[高兴]"}, {"url": "129.gif", alt: "[闲]"}, {
    "url": "130.gif",
    alt: "[努力]"
  }, {"url": "131.gif", alt: "[骂]"}, {"url": "132.gif", alt: "[疑问]"}, {
    "url": "133.gif",
    alt: "[秘密]"
  }, {"url": "134.gif", alt: "[乱]"}, {"url": "135.gif", alt: "[疯]"}, {
    "url": "136.gif",
    alt: "[哀]"
  }, {"url": "137.gif", alt: "[鬼]"}, {"url": "138.gif", alt: "[打击]"}, {
    "url": "139.gif",
    alt: "[bye]"
  }, {"url": "140.gif", alt: "[汗]"}, {"url": "141.gif", alt: "[抠]"}, {
    "url": "142.gif",
    alt: "[鼓掌]"
  }, {"url": "143.gif", alt: "[糟糕]"}, {"url": "144.gif", alt: "[恶搞]"}, {
    "url": "145.gif",
    alt: "[什么]"
  }, {"url": "146.gif", alt: "[什么]"}, {"url": "147.gif", alt: "[累]"},
  {"url": "148.gif", alt: "[看]"}, {"url": "149.gif", alt: "[难过]"}, {"url": "150.gif", alt: "[难过]"}, {
    "url": "151.gif",
    alt: "[坏]"
  }, {"url": "152.gif", alt: "[亲]"}, {"url": "153.gif", alt: "[吓]"}, {
    "url": "154.gif",
    alt: "[可怜]"
  }, {"url": "155.gif", alt: "[刀]"}, {"url": "156.gif", alt: "[水果]"}, {
    "url": "157.gif",
    alt: "[酒]"
  }, {"url": "158.gif", alt: "[篮球]"}, {"url": "159.gif", alt: "[乒乓]"}, {
    "url": "160.gif",
    alt: "[咖啡]"
  }, {"url": "161.gif", alt: "[美食]"}, {"url": "162.gif", alt: "[动物]"}, {
    "url": "163.gif",
    alt: "[鲜花]"
  }, {"url": "164.gif", alt: "[枯]"}, {"url": "165.gif", alt: "[唇]"}, {
    "url": "166.gif",
    alt: "[爱]"
  }, {"url": "167.gif", alt: "[分手]"}, {"url": "168.gif", alt: "[生日]"}, {
    "url": "169.gif",
    alt: "[电]"
  }, {"url": "170.gif", alt: "[炸弹]"}, {"url": "171.gif", alt: "[刀子]"},
  {"url": "172.gif", alt: "[足球]"}, {"url": "173.gif", alt: "[瓢虫]"}, {"url": "174.gif", alt: "[翔]"}, {
    "url": "175.gif",
    alt: "[月亮]"
  }, {"url": "176.gif", alt: "[太阳]"}, {"url": "177.gif", alt: "[礼物]"}, {
    "url": "178.gif",
    alt: "[抱抱]"
  }, {"url": "179.gif", alt: "[拇指]"}, {"url": "180.gif", alt: "[贬低]"}, {
    "url": "181.gif",
    alt: "[握手]"
  }, {"url": "182.gif", alt: "[剪刀手]"}, {"url": "183.gif", alt: "[抱拳]"}, {
    "url": "184.gif",
    alt: "[勾引]"
  }, {"url": "185.gif", alt: "[拳头]"}, {"url": "186.gif", alt: "[小拇指]"}, {
    "url": "187.gif",
    alt: "[拇指八]"
  }, {"url": "188.gif", alt: "[食指]"}, {"url": "189.gif", alt: "[ok]"}, {
    "url": "190.gif",
    alt: "[情侣]"
  }, {"url": "191.gif", alt: "[爱心]"}, {"url": "192.gif", alt: "[蹦哒]"}, {
    "url": "193.gif",
    alt: "[颤抖]"
  }, {"url": "194.gif", alt: "[怄气]"}, {"url": "195.gif", alt: "[跳舞]"},
  {"url": "196.gif", alt: "[发呆]"}, {"url": "197.gif", alt: "[背着]"}, {
    "url": "198.gif",
    alt: "[伸手]"
  }, {"url": "199.gif", alt: "[耍帅]"}, {"url": "200.png", alt: "[微笑]"}, {
    "url": "201.png",
    alt: "[生病]"
  }, {"url": "202.png", alt: "[哭泣]"}, {"url": "203.png", alt: "[吐舌]"}, {
    "url": "204.png",
    alt: "[迷糊]"
  }, {"url": "205.png", alt: "[瞪眼]"}, {"url": "206.png", alt: "[恐怖]"}, {
    "url": "207.png",
    alt: "[忧愁]"
  }, {"url": "208.png", alt: "[眨眉]"}, {"url": "209.png", alt: "[闭眼]"}, {
    "url": "210.png",
    alt: "[鄙视]"
  }, {"url": "211.png", alt: "[阴暗]"}, {"url": "212.png", alt: "[小鬼]"}, {
    "url": "213.png",
    alt: "[礼物]"
  }, {"url": "214.png", alt: "[拜佛]"}, {"url": "215.png", alt: "[力量]"}, {
    "url": "216.png",
    alt: "[金钱]"
  }, {"url": "217.png", alt: "[蛋糕]"}, {"url": "218.png", alt: "[彩带]"}, {"url": "219.png", alt: "[礼物]"}]

let IMUI = null;
let currentContactId = null;
const otheruser = {
  id: "hehe",
  displayName: "客服",
  avatar: path.join(__static, "/img/im/face/face_14.jpg"),
};
var userId = null
var pullNext = {}

var wsTimer = null
var uname = ''
export default {
  props: ['visible'],
  data() {
    return {
      hideMenuAvatar: true,
      hideMenu: true,
      hideDrawer: true,
      myUser: {
        id: "user",
        displayName: "用户",
        avatar: path.join(__static, "/img/im/face/face_5.jpg")
      },
      contacts: {},
      kfIdArr: {},
      allkfData: {},
      kfId: '',
      kfname: '',
      msgList: {},
      kid: ''
    };
  },
  computed: {
    ...mapGetters([
      "uid",
    ])
  },
  watch: {
    visible(val) {
      if (val) {
        setTimeout(() => {
          this.initIMUI()
        }, 200)
      } else {
        IMUI = null
        currentContactId = null
      }
    }
  },
  mounted() {
    // 接收消息处理
    this.wsInit()
  },
  methods: {
    wsInit() {
      wsTimer = setInterval(() => {
        if (client) {
          client.on('message', (topic, message) => {
            this.wsOnMessage(topic, message.toString())
          })
          clearInterval(wsTimer)
        }
      }, 200)
    },
    close() {
      this.$emit('update:visible', false)
    },
    initIMUI() {
      IMUI = this.$refs.IMUI;
      if (!IMUI) {
        return false
      }

      for (const key in this.allkfData) {
        var status = this.allkfData[key].show ? '(在线)' : '(离线)'
        this.contacts['contact-' + key] = {
          id: 'contact-' + key,
          displayName: "客服: " + this.allkfData[key].name + status,
          avatar: path.join(__static, "/img/im/face/face_14.jpg"),
          type: "single",
          index: this.allkfData[key].name,
          unread: 0,
          lastSendTime: new Date().getTime(),
          lastContent: " "
        }
      }

      let data = Object.values(this.contacts);
      IMUI.initContacts(data);

      var emoji = []
      emojiList.forEach(function (item) {
        emoji.push(
            {
              name: item.alt,
              title: item.alt,
              src: path.join(__static, '/img/emoji/' + item.url)
            }
        )
      })
      IMUI.initEmoji(emoji);

      this.$nextTick(function () {
        this.updateContactsDom()
      })
    },
    updateContactsDom() {
      console.log(this.allkfData)
      var dom = document.getElementsByClassName('lemon-contact__name')
      var color1 = '#35d863'
      var color2 = '#909399'
      var color = ''
      for (let i = 0; i < dom.length; i++) {
        var name = dom[i].innerText
        name = name.split('(')
        var flag = 1
        var str = ''
        for (const allkfDataKey in this.allkfData) {
          if (name[0].indexOf(this.allkfData[allkfDataKey].name) > -1) {
            flag = this.allkfData[allkfDataKey].show
            break
          }
        }
        if (flag) {
          str = '(在线)'
          color = color1
        } else {
          str = '(离线)'
          color = color2
        }
        dom[i].innerHTML = name[0] + `<em style="color: ${color};font-style: normal">${str}</em>`
      }
    },
    initContactsDom() {
      var dom = document.getElementsByClassName('lemon-contact__name')
      for (let i = 0; i < dom.length; i++) {
        dom[i].innerHTML = dom[i].innerText
      }
    },
    handleMessageClick(e, key, message) {
      const {IMUI} = this.$refs;

      if (key == "status") {
        IMUI.updateMessage(message.id, message.toContactId, {
          status: "going",
          content: "正在重新发送消息..."
        });
        setTimeout(() => {
          IMUI.updateMessage(message.id, message.toContactId, {
            status: "succeed",
            content: "发送成功"
          });
        }, 2000);
      }
    },
    appendMessage() {
      const {IMUI} = this.$refs;
      const contact = IMUI.currentContact;
      const message = generateMessage();
      message.fromUser = {
        ...message.fromUser,
        ...this.myUser
      };
      IMUI.appendMessage(message);
      IMUI.updateContact(contact.id, {
        unread: "+1",
        lastSendTime: getTime(),
        lastContent: IMUI.lastContentRender(message)
      });
    },
    updateContact() {
      for (const key in this.allkfData) {
        var status = this.allkfData[key].show ? '(在线)' : '(离线)'
        IMUI.updateContact('contact-' + key, {
          displayName: "客服: " + this.allkfData[key].name + status
        });
      }

      setTimeout(() => {
        this.updateContactsDom()
      }, 200)
    },
    changeLoading() {
      var dom = document.getElementsByClassName('lemon-messages__load lemon-messages__load--ing')
      for (let i = 0; i < dom.length; i++) {
        dom[i].innerHTML = '<span>暂无更多消息</span>'
      }
    },
    handleChangeContact(contact) {
      console.log("Event:change-contact");
      this.$refs.IMUI.updateContact(contact.id, {
        unread: 0
      });
      this.changeLoading()
      currentContactId = contact.id
      this.kid = currentContactId.split('-')[1]
      this.contacts[currentContactId].unread = 0

      let result = this.msgList[currentContactId] || []
      var flag = true
      // result.reverse()
      result.forEach(item => {
        flag = false
        if (item.unSet) {
          item.unSet = 0
          setTimeout(() => {
            IMUI.appendMessage(item);
          }, 100)
        }
      })
    },
    handleSend(message, next, file) {
      //console.log("Event:send");
      console.log(message, next, file)
      var isemoji = false
      var content = message.content
      if (content.indexOf('[![') == 0 && content.indexOf(']]') == content.length - 2) {
        isemoji = true
      }
      var toMsg = content
      if (isemoji) {
        var emoji = message.content.match(/[\u4e00-\u9fa5]/g).join("");
        emojiList.forEach(item => {
          var arr = item.alt.split('')
          arr = arr.filter(item => item != '[' && item != ']')
          var i_emoji = arr.join("")
          if (i_emoji == emoji) {
            var emojiUrl = path.join(__static, `/img/emoji/${item.url}`)
            var img = `<img src='${emojiUrl}'>`
            var img2 = `<img src='./static/img/emoji/${item.url}'>`
            message.content = `<div style='display: flex;align-items: center;word-wrap:break-word;'>${img}</div>`
            toMsg = `<div style='display: flex;align-items: center;word-wrap:break-word;'>${img2}</div>`
          }
        })
      }
      message.status = 'succeed'
      next(message)
      var name = this.kid;
      var msg = {
        type: 'user',
        content: {
          "fromID": this.uid,
          "toID": name,
          "msg": BASE64.base64encode(BASE64.utf16to8(toMsg)),
          "time": new Date().getTime()
        }
      }
      console.log(msg)
      // 发送消息
      client.publish(`chating/customer/${this.uid}/${this.kid}`, JSON.stringify(msg), function () {
        console.log("发送成功：" + JSON.stringify(msg))
      })
    },
    handlePullMessages(contact, next) {
      console.log("Event:pull-messages");
      pullNext = next

      this.getHisData()
      next([], true)
    },
    getHisData() {
      client.publish(`chating/history/${this.kid}`, this.uid, () => {
        console.log("发送成功：" + this.kid)
      })
    },
    getname(username) {
      var disLength = username.length;
      username = username.substring(disLength - 3, disLength);
      return username
    },
    getkfend() {
      var keys = Object.keys(this.kfIdArr)
      var values = Object.values(this.kfIdArr)
      if (keys.length == 0) {
      } else if (!this.kfId) {
        this.kfId = keys[Math.floor(Math.random() * keys.length)]
        this.kfname = this.getname(values[Math.floor(Math.random() * values.length)])
      } else {
        if (keys.indexOf(this.kfId) == -1) {
          this.kfId = keys[Math.floor(Math.random() * keys.length)]
          this.kfname = this.getname(values[Math.floor(Math.random() * values.length)])
        }
      }
    },
    wsOnMessage(topic, data) {
      var Topic = topic.split('/')
      // 获取客服消息
      if (Topic[0] == 'kflist') {
        let result = JSON.parse(data)
        if (Topic[2] !== 'kf0') {
          this.allkfData[Topic[2]] = {
            name: this.getname(Topic[3]),
            show: result
          }
          if (IMUI) {
            this.updateContact()
          }
        }
      }
      if (Topic[0] == 'chating' && Topic[1] == 'customerSer') {
        var result = JSON.parse(data)
        var msg = BASE64.utf8to16(BASE64.base64decode(result.content.msg))
        var fromUser = null;
        if (result.content.toID === this.uid) {
          fromUser = otheruser
        } else {
          fromUser = this.myUser
        }
        let msgData = {
          id: generateRandId(),
          status: "succeed",
          type: "text",
          sendTime: result.content.time,
          content: msg,
          toContactId: "contact-" + this.kid,
          fromUser,
          unSet: 1
        }
        var newParams = {
          lastSendTime: new Date().getTime(),
          lastContent: msg,
          unread: 0
        }
        if (currentContactId == "contact-" + this.kid) {
          msgData.unSet = 0
          unread = 0
          IMUI && IMUI.appendMessage(msgData);
        }
        var unread = this.contacts[currentContactId].unread
        if (!this.msgList["contact-" + this.kid]) {
          this.msgList["contact-" + this.kid] = [msgData]
          unread++
        } else {
          this.msgList["contact-" + this.kid].push(msgData)
          unread++
        }
        if (currentContactId == "contact-" + this.kid) {
          unread = 0
        }
        newParams.unread = unread
        IMUI && IMUI.updateContact("contact-" + this.kid, newParams)
      }
      if (Topic[0] == 'chating' && Topic[1] == 'hisCustomerSer') {
        var result = JSON.parse(data)
        console.log(result)
        var hisArr = []
        result.content.forEach(item => {
          var key1 = 'contact-' + item.fromID
          var key2 = 'contact-' + item.toID
          if (this.contacts[key1]) {
            let rsMsgData = {
              id: generateRandId(),
              status: "succeed",
              //消息类型 voice | file | video | image | text
              type: "text",
              sendTime: item.time,
              content: BASE64.utf8to16(BASE64.base64decode(item.msg)),
              toContactId: key1,
              fromUser: otheruser
            }
            hisArr.push(rsMsgData)
          } else if (this.contacts[key2]) {
            let rsMsgData = {
              status: "succeed",
              //消息类型 voice | file | video | image | text
              type: "text",
              id: generateRandId(),
              sendTime: item.time,
              content: BASE64.utf8to16(BASE64.base64decode(item.msg)),
              toContactId: key2,
              fromUser: this.myUser
            }
            hisArr.push(rsMsgData)
          }
        })
        if (IMUI) {
          pullNext(hisArr, true)
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">
.imui-center-wrap {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.imui-center {
  position: fixed;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);

  .cover {
    text-align: center;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);

    i {
      font-size: 84px;
      color: #e6e6e6;
    }

    p {
      font-size: 18px;
      color: #ddd;
      line-height: 50px;
    }
  }

  /deep/ .lemon-sidebar {
    .bar-wrap {
      height: 60px;
      position: sticky;
      top: 0;
      background: #efefef;
      z-index: 2;
      overflow: hidden;
      border-bottom: 1px solid #cecece;
    }
  }

  .bar {
    text-align: center;
    line-height: 30px;
    background: #fff;
    margin: 15px;
    color: #666;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    font-size: 12px;
  }

  /deep/ .lemon-editor__tool {
    & > .lemon-editor__tool-item {
      display: none;
    }
  }

  /deep/ .lemon-editor__footer {
    .lemon-editor__tip {
      display: none;
    }
  }

  /deep/ .lemon-messages__load.lemon-messages__load--ing {
    span {
      text-align: center;
      font-size: 12px;
      color: #999;
      line-height: 30px;
    }
  }

  .close {
    width: 30px;
    height: 30px;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1000;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      background: #cecece;
    }

    i {
      font-size: 24px;
      color: #606266;
    }
  }
}
</style>
